#include <stdio.h>
#include <string.h>
#include "option.h"

int g_optind = 1;
const char* g_optarg = NULL;
int getopt_long (int ___argc,
				 char *const *___argv,
				 const char *__shortopts,
		         const struct option *__longopts, 
				 int *__longind)
{
	if(___argc==0)
		return -1;
	if(___argc == g_optind)
		return -1;

	*__longind = 0;
	const char* opt = ___argv[g_optind++];
	if(*opt++ != '-')
		return '?';
	if(*opt == 0)
		return '?';
	if(*opt == '-' && *++opt ==0)
		return '?';
	bool long_opt = strlen(opt)>1 || strchr(__shortopts, *opt)==NULL;
	if(long_opt)
	{
		const struct option* lo = __longopts;
        char temp[128]={0};
		for(;;++lo)
		{
            strcpy(temp, opt);
			if(NULL == lo->name) return '?';
            char* eq = strchr(temp, '=');
            if(eq) *eq++ = 0;
			if(strcmp(lo->name, temp)) {++*__longind; continue;}
			if(!lo->has_arg) return 0;
            if(eq)
                g_optarg = strchr(opt,'=')+1;
            else
                g_optarg = ___argv[g_optind++];
			return 0;
		}
	}
	else
	{
		const char* p = strchr(__shortopts, *opt);
		if(*++p == ':') g_optarg = ___argv[g_optind++];
		return *opt;
	}

}
